#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    setFixedSize(500, 500);
    ui->setupUi(this);

    scene = new QGraphicsScene(this);

    ui->graphicsView->resize(500, 500);
    scene->setSceneRect(0,0,500,500);
    ui->graphicsView->setScene(scene);
    ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);


    QTime randomizer(0, 0, 0);
    qsrand(randomizer.secsTo(QTime::currentTime()));
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(startThread()));

    thread = new MyThread(&transparancy);
    connect(thread, SIGNAL(send(QGraphicsItem*)), this, SLOT(drowGraphicItem(QGraphicsItem*)));
    connect(thread, SIGNAL(finished()), this, SLOT(stopThread()));

    int n = QMessageBox::warning(0,
                                 "ACHTUNG!",
                                 "hello my friend"
                                 "\nDo you want to open previously generated items?",
                                 "Yes",
                                 "No",
                                 QString(),
                                 0,
                                 1
                                );

    if(!n) {
        loadData();
    }


}

MainWindow::~MainWindow()
{
    if (scene != nullptr) {
        scene->clear();
        delete scene;
    }
    if (timer != nullptr) {
        delete timer;
    }
    if (thread != nullptr) {
        delete thread;
    }
    if (ui != nullptr) {
        delete ui;
    }

}

void MainWindow::saveData()
{
    QFile file("saveddata.txt");

    if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return;
    }
    QTextStream out(&file);
    list = scene->items();
    for (int i = 0; i < list.length(); i++) {
        out << list[i]->data(0).toChar() << '\n';
        QRectF tmp = list[i]->boundingRect();
        out << (int)tmp.x() << '\n' << (int)tmp.y() << '\n' << (int)tmp.width() << '\n' << (int)tmp.height() << '\n';
    }

    saveDataToPixMap();
    file.close();
}

void MainWindow::loadData()
{
    QFile file("saveddata.txt");

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return;
    }
    QTextStream in(&file);
    while (!in.atEnd()) {
        char figure;
        int x, y, w, h;
        in >> figure;
        in >> x;
        in >> y;
        in >> w;
        in >> h;
        if (figure == 'C') {
            scene->addEllipse(x, y, w, h, QPen(Qt::blue, 1, Qt::SolidLine), QBrush(QColor(0, 0, 255, transparancy)))->setData(0, 'C');
        }
        if (figure == 'S') {
            scene->addRect(x, y, w, h, QPen(Qt::green, 1, Qt::SolidLine), QBrush(QColor(0, 255, 0, transparancy)))->setData(0, 'S');
        }
        if (figure == 'R') {
            scene->addRect(x, y, w, h,  QPen(Qt::red, 1, Qt::SolidLine), QBrush(QColor(255, 0, 0, transparancy)))->setData(0, 'R');
        }

    }
    file.close();
}

void MainWindow::changeTransparency()
{
    list = scene->items();
    thread->setTransparency(transparancy);
    for (int i = 0; i < list.length(); i++) {
        QGraphicsRectItem* item = (QGraphicsRectItem*) (list[i]);
        if (list[i]->data(0) == 'C') {
           item->setBrush(QBrush(QColor(0, 0, 255, transparancy)));
        }
        if (list[i]->data(0) == 'S') {
           item->setBrush(QBrush(QColor(0, 255, 0, transparancy)));
        }
        if (list[i]->data(0) == 'R') {
           item->setBrush(QBrush(QColor(255, 0, 0, transparancy)));
        }
    }

}

void MainWindow::saveDataToPixMap()
{
    QPixmap pixmap = ui->graphicsView->grab();
    pixmap.save("pixmap.png");
}

void MainWindow::startThread()
{
    qDebug() << "start";
    if (!threadActive) {
        threadActive = true;
        thread->start();
    }
}

void MainWindow::stopThread()
{
    qDebug() << "stop";
    threadActive = false;
}

void MainWindow::drowGraphicItem(QGraphicsItem *item)
{
    scene->addItem(item);
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Space){
        if (keepGen == true) {
            timer->stop();
            keepGen = false;
            int n = QMessageBox::warning(0,
                                         "ACHTUNG!",
                                         "You've stopped the generation"
                                         "\nDo you want to save generated items?",
                                         "Yes",
                                         "No",
                                         QString(),
                                         0,
                                         1
                                        );
            if(!n) {
                saveData();
            }


        } else {
            keepGen = true;
            timer->start(1000);
        }
    }

    if (event->key() == Qt::Key_W) {
        if (transparancy <= 245) {
            transparancy += 25;
            changeTransparency();
        }
    }

    if (event->key() == Qt::Key_S) {
        if (transparancy >= 10 ) {
            transparancy -= 25;
            changeTransparency();
        }
    }

}


